package com.docparser;

import java.io.File;
import java.io.FileWriter;

import com.docparser.converters.HtmlConverter;
import com.docparser.processor.DocxProcessor;

/**
 * Main class that orchestrates the document parsing process.
 * Coordinates between document processing and HTML generation components
 * to convert DOCX documents with mathematical formulas to HTML.
 */
public class DocParser {
    /**
     * Main entry point for the document parsing application.
     * Reads a DOCX file, extracts mathematical formulas, and generates
     * an HTML file with MathJax-rendered formulas.
     *
     * @param args Command line arguments (not used)
     */
    public static void main(String[] args) {
        try {
            String inputFile = "b.docx";
            String outputFile = "b.html";
            
            // 增加命令行参数处理
            if (args.length >= 2) {
                inputFile = args[0];
                outputFile = args[1];
            }

            if (!inputFile.toLowerCase().endsWith(".docx")) {
                System.err.println("错误: 仅支持DOCX文件.");
                return;
            }

            // 检查输入文件是否存在
            File docxFile = new File(inputFile);
            if (!docxFile.exists()) {
                System.err.println("错误: 输入文件 " + inputFile + " 不存在");
                return;
            }
            
            System.out.println("开始处理文件: " + inputFile);
            
            // Initialize components
            HtmlConverter htmlConverter = new HtmlConverter();
            DocxProcessor docxProcessor = new DocxProcessor(inputFile);
            
            // 添加公式计数器
            final int[] formulaCount = {0};
            
            // Process the document and convert formulas to HTML
            docxProcessor.process(formula -> {
                htmlConverter.addFormula(formula);
                formulaCount[0]++;
                System.out.println("已处理公式数量: " + formulaCount[0]);
            });
            
            // Write the final HTML to file
            try (FileWriter writer = new FileWriter(outputFile)) {
                writer.write(htmlConverter.getHtml());
            }
            
            System.out.println("转换完成!");
            System.out.println("总共处理公式数量: " + formulaCount[0]);
            System.out.println("输出文件: " + outputFile);
            
        } catch (Exception e) {
            System.err.println("转换过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
